package cn.dankal.flyaudio.personal;

import android.content.Intent;
import android.view.View;
import android.widget.Toast;

import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.MyCardServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.CouponEntity;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.SelectCardAdapter;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import cn.dankal.flyaudio.contract.MyCardContract;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.dankal.flyaudio.presenter.MyCardPresenter;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

/**
 * <pre>
 *     e-mail : junfeng.nie@duntech.com.cn
 *     time   : 15/7/2020
 *     desc   :
 *     version: cn.dankal.flyaudio.personal
 *     Copyright: Copyright（c）2018
 *     Company:
 * </pre>
 *
 * @author niejunfeng
 */
public class SelectCardActivity extends BaseActivity implements MyCardContract.View {

    SelectCardAdapter adapter;

    private RecyclerView recyclerView;


    private MyCardPresenter mPresenter;
    private MultipleStatusView statusView;

    private int page = 1;

    @Override
    public void showProductList(List<CouponEntity> data) {
        List<CouponEntity> couponEntities = new ArrayList<>();
        for (CouponEntity entity : data) {
            if (entity.getCanTransfer()) {
                couponEntities.add(entity);
            }
        }
        if (couponEntities.isEmpty()) {
            statusView.showEmpty();
            return;
        }
        statusView.showContent();
        adapter.addDatas(couponEntities, false);
    }

    @Override
    public void onError() {
        statusView.showError();
    }

    @Override
    public void onExchangeSuccess(String id) {

    }

    @Override
    public void onExchangeError() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_card;
    }

    @Override
    protected void initComponents() {
        recyclerView = findViewById(R.id.list);
        adapter = new SelectCardAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        statusView = findViewById(R.id.multiple_status_view);
        mPresenter = new MyCardPresenter();
        mPresenter.attachView(this);

        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mPresenter.getDataList(page, "USABLE");
        LiveEventBus.get(LiveDataBusConstant.PICK_COUPON_RESULT, CouponEntity.class).observe(this, new Observer<CouponEntity>() {
            @Override
            public void onChanged(CouponEntity couponEntity) {
                ConversationType convType = (ConversationType) getIntent().getSerializableExtra(FlyApplication.CONV_TYPE);
                String targetId = getIntent().getStringExtra(FlyApplication.TARGET_ID);
                Conversation conv = null;
                if (convType != null) {
                    switch (convType) {
                        case single:
                            doSendReq(couponEntity, targetId);
                            break;
                        case group:
                            doSendReqByGroup(couponEntity, targetId);
                            break;
                        case chatroom:
                            break;
                        default:
                    }
                }
            }
        });
    }

    private void send(CouponEntity couponEntity, String transferOrderUuid) {
        ConversationType convType = (ConversationType) getIntent().getSerializableExtra(FlyApplication.CONV_TYPE);
        String targetId = getIntent().getStringExtra(FlyApplication.TARGET_ID);
        String targetAppKey = getIntent().getStringExtra(FlyApplication.TARGET_APP_KEY);
        Conversation conv = null;
        if (convType != null) {
            switch (convType) {
                case single:
                    conv = JMessageClient.getSingleConversation(targetId, targetAppKey);
                    break;
                case group:
                    conv = JMessageClient.getGroupConversation(Long.valueOf(targetId));
                    break;
                case chatroom:
                    conv = JMessageClient.getChatRoomConversation(Long.valueOf(targetId));
                    break;
                default:
            }
        }
        CustomContent customContent = new CustomContent();
        customContent.setStringExtra("coupon_id", transferOrderUuid);
        customContent.setStringExtra("sendCoupon", "sendCoupon");
        customContent.setStringExtra("couponName", couponEntity.getName());
        Message textMessage = conv.createSendMessage(customContent);
        MessageSendingOptions options = new MessageSendingOptions();
        options.setNeedReadReceipt(true);
        JMessageClient.sendMessage(textMessage, options);
        textMessage.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    SharePreferenceManager.setIsOpen(true);
                    Toast.makeText(SelectCardActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.putExtra(FlyApplication.MSG_JSON, textMessage.toJson());
                    SelectCardActivity.this.setResult(RESULT_OK, intent);
                    finish();
                } else {
                    HandleResponseCode.onHandle(SelectCardActivity.this, i, false);
                }
            }
        });
    }

    private void doSendReqByGroup(CouponEntity couponId, String groupId) {
        showLoadingDialog();
        MyCardServiceFactory.couponsExchangeByGroup(couponId.getUuid(), groupId)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        send(couponId, objectBaseResponse.getData());
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }

    private void doSendReq(CouponEntity couponId, String userId) {
        showLoadingDialog();
        MyCardServiceFactory.couponsExchange(couponId.getUuid(), userId)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        send(couponId, objectBaseResponse.getData());
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }
}
